package com.mapfinal.server.auth;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.lambkit.Lambkit;
import com.lambkit.common.util.StringUtils;
import com.mapfinal.server.MapfinalServerConfig;
import com.mapfinal.server.auth.model.AuthRule;
import com.mapfinal.server.auth.model.Role;
import com.mapfinal.server.auth.model.User;

public class AuthRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		String username = (String) principals.getPrimaryPrincipal();
        System.out.println("realm username: " + username);
        User authUser = User.service().findByUserName(username);
        
        if(authUser.getId()==1){
        	SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        	//超级管理员 始终拥有所有权限
        	info.addRole("super");
            info.addStringPermission("*");
            return info;
        }

        // 当前用户所有角色
        List<Role> authRoles = Role.service().getRoles(authUser.getId());
        Set<String> roles = new HashSet<>();
        for (Role authRole : authRoles) {
            if (StringUtils.isNotBlank(authRole.getName())) {
                roles.add(authRole.getName());
            }
        }

        // 当前用户所有权限
        List<AuthRule> upmsPermissions = AuthRule.service().getPermissions(authUser.getId());
        Set<String> permissions = new HashSet<>();
        for (AuthRule upmsPermission : upmsPermissions) {
            if (StringUtils.isNotBlank(upmsPermission.getValue())) {
                permissions.add(upmsPermission.getValue());
            }
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        MapfinalServerConfig authConfig = Lambkit.config(MapfinalServerConfig.class);
        // client无密认证
        String upmsType = authConfig.getRpcType();
        if ("client".equals(upmsType)) {
            return new SimpleAuthenticationInfo(username, password, getName());
        }
        // 查询用户信息
        User upmsUser = User.service().findByLoginName(username);
        if (null == upmsUser) {
            throw new UnknownAccountException();
        }
        if (!upmsUser.getPassword().equals(User.service().getPasswordSecurity(password + upmsUser.getSalt()))) {
            throw new IncorrectCredentialsException();
        }
        if (upmsUser.getUserStatus() == 0) {
            throw new LockedAccountException();
        }
        username = upmsUser.getUserLogin();
        return new SimpleAuthenticationInfo(username, password, getName());
	}

}
